package com.ycy.chuwenuniapp.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ycy.chuwenuniapp.common.Constant;
import com.ycy.chuwenuniapp.common.ResCodeEnum;
import com.ycy.chuwenuniapp.common.ResData;
import com.ycy.chuwenuniapp.entity.User;
import com.ycy.chuwenuniapp.exception.CustomException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Service
public class LoginService {
    @Resource
    private UserService userService;

    public ResData<User> uniAppLogin(String code) {
        if(StrUtil.isBlank(code)) throw new CustomException(ResCodeEnum.BAD_REQUEST,"调用登录接口缺少code参数");

        String url = Constant.GET_LOGIN_URL.replace("APPID",Constant.APP_ID).replace("APPSECRET",Constant.APP_SECRET).replace("CODE",code);
        String result = HttpUtil.get(url);
        System.out.println("从微信获取的用户信息："+ result);
        JSONObject res = JSON.parseObject(result);
        String openId = res.get("openid").toString();

        List<User> userList = userService.findAll(openId, "");
        if(userList.size() == 1)  return ResData.success(userList.get(0));
        else if(userList.size() == 0) {
            User user = new User();
            String userId = IdUtil.getSnowflakeNextIdStr();
            user.setId(userId);
            user.setIsAdmin(0);
            user.setOpenId(openId);
            user.setName("初吻-"+ StrUtil.sub(userId, -5, userId.length()));
            Boolean isSave = userService.saveUser(user).getData();
            if(isSave) return ResData.success(user);
            else throw new CustomException(ResCodeEnum.SERVER_ERROR,"系统错误,登陆失败");
        }else throw new CustomException(ResCodeEnum.SERVER_ERROR,"错误的存在多个该openid的账号");
    }
}
